#!/usr/bin/env python
#
#       MajeRe_GUI_rewrite.py
#       
#       Copyright 2009 Brandon Invergo <brandon@brandoninvergo.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.


import sys
import locale

try:
    import pygtk
    #tell pyGTK, if possible, that we want GTKv2
    pygtk.require("2.0")
except:
    #Some distributions come with GTK2, but not pyGTK
    pass

try:
    import gtk
    import gtk.glade
    
except:
    print "You need to install pyGTK or GTKv2 ",
    print "or set your PYTHONPATH correctly."
    print "try: export PYTHONPATH=",
    print "/usr/local/lib/python2.2/site-packages/"
    sys.exit(1)

import MajeRe_Engine
import Script_tab
import Data_tab     
    
class Open_script_dialog:
    encoding = locale.getlocale()[1]
    utf8conv = lambda self, x : unicode(x, self.encoding).encode('utf8')
    
    def on_open_script_open_button(self, widget):
        try:
            opened_script = open(self.dialog.get_filename(),"r")
        except:
            self.error.show_error("Error opening file")
        content = opened_script.read()
        try:
            content = self.utf8conv(content)  
        except:
            self.error.show_error("Unsupported file type.")
        else:
            self.main_window.script.script_buffer.set_text(content)
            opened_script.close()
            self.dialog.hide()
            
    def on_open_script_cancel_button(self, widget):
        self.hide()
        
    def __init__(self, parent_window, glade_gui):
        self.main_window = parent_window
        self.glade_gui = glade_gui
        self.error = Error_dialog(glade_gui)
        
        callbacks = {"on_open_script_open_button" : self.on_open_script_open_button,\
        "on_open_script_cancel_button" : self.on_open_script_cancel_button}
        
        self.glade_gui.signal_autoconnect(callbacks)
        
        self.dialog = self.glade_gui.get_widget("Open_script_file_chooser")
        self.dialog.show()
    
class Export_script_dialog:
    def on_export_script_save_button(self, widget):
        try:
            new_file = open(self.dialog.get_filename(), "w")
        except:
            self.error.show_error("Error opening file for writing.")
        else:
            try:
                new_file.write(self.script)
            except:
                self.error.show_error("Error writing file.")
            else:
                self.dialog.hide()
                
    def on_export_script_cancel_button(self, widget):
        self.dialog.hide()
        
    def __init__(self, parent_window, glade_gui, script):
        self.main_window = parent_window
        self.glade_gui = glade_gui
        self.error = Error_dialog(glade_gui)
        self.script = script
        
        callbacks = {"on_export_script_save_button" : self.on_export_script_save_button,\
            "on_export_script_cancel_button" : self.on_export_script_cancel_button}
        self.glade_gui.signal_autoconnect(callbacks)
        
        self.dialog = self.glade_gui.get_widget("Export_script_file_chooser")
        self.dialog.show()
        
class Error_dialog:
    def show_error(self, error_string):
        self.label.set_text(error_string)
        self.dialog.show()
        
    def on_error_button(self, widget):
        self.dialog.hide()
        
    def __init__(self, glade_gui):
        self.glade_gui = glade_gui
        self.dialog = self.glade_gui.get_widget("Error_dialog")
        self.label = self.glade_gui.get_widget("Error_label")
        
        callbacks = {"on_error_button" : self.on_error_button}
        
        self.glade_gui.signal_autoconnect(callbacks)
    
class MajeRe_Gui:
    r_eng = MajeRe_Engine.MajeRe_Engine()
    clipboard = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)
    
    def on_menu_open_script(self, widget):
        Open_script_dialog(self, self.glade_gui)
        
    def on_menu_export_script(self, widget):
        start_iter = self.script.script_buffer.get_start_iter()
        end_iter = self.script.script_buffer.get_end_iter()
        script = self.script.script_buffer.get_text(start_iter,end_iter)
        Export_script_dialog(self, self.glade_gui, script)
        
    def on_menu_cut(self, widget):
        if self.main_window.get_focus() == self.script.script_textview:
            self.script.script_buffer_cut(self.clipboard, True)
        elif self.main_window.get_focus() == self.script.console_entry:
            self.script.console_entry_cut()

    def on_menu_copy(self, widget):
        if self.main_window.get_focus() == self.script.script_textview:
            self.script.script_buffer_copy(self.clipboard)
        elif self.main_window.get_focus() == self.script.console_output:
            self.script.console_buffer_copy(self.clipboard)
        elif self.main_window.get_focus() == self.script.console_entry:
            self.script.console_entry_copy()
            
    def on_menu_paste(self, widget):
        if self.main_window.get_focus() == self.script.script_textview:
            self.script.script_buffer_paste(self.clipboard)
        elif self.main_window.get_focus() == self.script.console_entry:
            self.script.console_entry_paste()
        
    def on_menu_undo(self, widget):
        if self.main_window.get_focus() == self.script.script_textview:
           self.script.undo()
            
    def on_menu_redo(self, widget):
        self.script.redo()

    def on_menu_undo(self, widget):
        self.script.undo()
    
    def close_application(self, widget):
        gtk.main_quit()
             
    def do_R_command(self, command):
        """This function interacts with R by sending commands to it"""
        if command == "":
            return False
        res = self.r_eng.R(command)
        self.data.update_data_view()
        return res

    def __init__(self):
        # Load the Glade GUI
        gladefile="MajeRe.glade"
        self.glade_gui = gtk.glade.XML(gladefile)
        
        self.main_window = self.glade_gui.get_widget("Main_window")
        
        main_callbacks = {"gtk_main_quit" : self.close_application, \
            "on_menu_open_script" : self.on_menu_open_script, \
            "on_menu_export_script" : self.on_menu_export_script, \
            "on_menu_copy" : self.on_menu_copy, \
            "on_menu_cut"  : self.on_menu_cut, \
            "on_menu_paste": self.on_menu_paste, \
            "on_menu_undo" : self.on_menu_undo, \
            "on_menu_redo" : self.on_menu_redo}
        self.glade_gui.signal_autoconnect(main_callbacks)
        
        self.script = Script_tab.Script_tab(self, self.glade_gui)
        self.data = Data_tab.Data_tab(self, self.glade_gui)
    
def main():
    """The main function"""
    # Enter the main Gtk loop
    gtk.main()
    return 0
        
if __name__ == "__main__":
    MajeRe_Gui()
    main()  

